'''
meteonorm可以通过传入xml文件进行批量的数据导出，
这个脚本是将excel文件写为xml文件。
'''
import os
import xml
import xml.etree.ElementTree as ET
import uuid
import pandas as pd


def generate_xml(locations):
    # Create the root element
    root = ET.Element("userdefinedlocations")

    for name, lat, lon in locations:
        # Create a location element
        location = ET.SubElement(root, "location")
        location.set("id", str(uuid.uuid4()))

        # Add child elements
        ET.SubElement(location, "name").text = name
        ET.SubElement(location, "latitude").text = str(lat)
        ET.SubElement(location, "longitude").text = str(lon)
        ET.SubElement(location, "timezone").text = "8"
        ET.SubElement(location, "timereference").text = "-30"
        ET.SubElement(location, "situation").text = "Open"
    return ET.tostring(root, encoding="utf-8", method="xml").decode("utf-8")

if __name__ == "__main__":
    pin_stations_path = r"../file/meteonorm_input"
    filename = '重庆市网格化结果.xlsx'
    pin_info = pd.read_excel(os.path.join(pin_stations_path, filename))

    # todo: meteonorm的数据批处理仅支持到最多100个：分批处理，生成文件：
    '''
    # 这里的name就是文件存储用的名字
    '''
    for i in range(0, len(pin_info), 100):
        locations = []
        for row in pin_info.iloc[i:i+100].iterrows():
            name = row[1]['省']+'_'+ row[1]['市']+'_'+row[1]['区县']+'_'+ str(row[1]['lon']) +'_'+ str(row[1]['lat'])
            locations.append((name, row[1]['lat'], row[1]['lon']))
        xml_output = generate_xml(locations)
        # Optionally, save to a file
        savepath = os.path.join(r'D:\work_files\code\grided_district\file\meteonorm_xml',
                                filename.split('.')[0] + '_' + str(i//100) + '.xml')
        with open(savepath, "w", encoding="utf-8") as f:
            f.write('<?xml version="1.0" encoding="utf-8"?>\n')
            f.write(xml_output)
    # xml_output = generate_xml(locations)
    # print(xml_output)

